﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Collections;

namespace CitrixPVSWrapper
{

    [System.Management.Automation.Cmdlet("Run", "PvsServerCount", SupportsShouldProcess = true)]
    public class Run_PvsServerCount : System.Management.Automation.PSCmdlet
    {

        [Parameter(ParameterSetName = "Site", Mandatory = true)]
        public PvsSite Site;

        [Parameter(ParameterSetName = "SiteId", ValueFromPipelineByPropertyName = true, Mandatory = true)]
        public string SiteId;

        [Parameter(ParameterSetName = "SiteName", Mandatory = true)]
        public string SiteName;

        protected override void ProcessRecord()
        {
            // Verbose and Debug Settings
            Boolean Verbose = this.MyInvocation.BoundParameters.ContainsKey("Verbose");
            WriteVerbose("Verbose Flag: " + Verbose);
            Boolean Debug = this.MyInvocation.BoundParameters.ContainsKey("Debug");
            WriteDebug("Debug Flag: " + Debug);

            // Collections to hold the queries and the results
            Collection<QueryDefinition> RunQueries = new Collection<QueryDefinition>();
            string TargetObject = "ServerCount";

            // Build the queries based on the parameter sets
            switch (this.ParameterSetName)
            {
                case "Site":
                    {
                        RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "SiteId=\"" + this.Site.SiteId + "\""));
                        break;
                    }

                case "SiteId":
                    {
                        RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "SiteId=\"" + this.SiteId + "\""));
                        break;
                    }

                case "SiteName":
                    {
                        foreach (PvsSite QrySite in Get_PvsSite_Internal.Get_SiteByName(this.SiteName, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "SiteId=\"" + QrySite.SiteId + "\"")); }
                        break;
                    }

            }

            // Test that we have a suitable object to perform the Run with, and build the confirmation message
            if (RunQueries.Count() == 0)
            {
                WriteError(new ErrorRecord(new InvalidOperationException("No items were found to get the server count for using the supplied parameters"), "1", ErrorCategory.InvalidArgument, null));
            }

            // Execute the run queries
            foreach (QueryDefinition RunQuery in RunQueries)
            {

                string objectId;
                string objectName;
                string ShouldProcessMessage;

                // Check that we have a valid parameter to work with, extract the object id/name and build the ShouldProcess message
                if (RunQuery.Parameters.Where(p => p.StartsWith("ServerId")).Count() == 1)
                {
                    objectId = RunQuery.Parameters.Where(p => p.StartsWith("ServerId")).First().Split('=')[1].Replace('"', ' ').Trim();
                    if (Get_PvsServer_Internal.Get_ServerById(objectId).Count() != 1)
                    {
                        WriteError(new ErrorRecord(new InvalidOperationException(String.Format("Server Id {0} does not exist", objectId)), "2", ErrorCategory.InvalidArgument, null));
                        continue;
                    }
                    objectName = Get_PvsServer_Internal.Get_ServerById(objectId).First().ServerName;
                    ShouldProcessMessage = String.Format("Get server count for site {0} with site Id {1}", objectName, objectId);
                }

                else
                {
                    WriteError(new ErrorRecord(new InvalidOperationException("Query does not contain any valid targets"), "2", ErrorCategory.InvalidArgument, null));
                    continue;
                }

                // Perform the actual run and return any errors
                if (ShouldProcess(ShouldProcessMessage))
                {
                    foreach (string[] Record in PvsHelpers.ExecuteMcliQuery(RunQuery, Verbose, Debug))
                    {
                        WriteDebug("Returning Object");
                        WriteObject(PvsHelpers.Get_UInt32ValueFromRecord("ServerCount", Record, Verbose));
                    }
                }

            }

        }
    }
}
